import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_app/models/house_details_data.dart';
import 'package:flutter_app/pages/home/info/info_item.dart';
import 'package:flutter_app/pages/release_house/room_configuration.dart';
import 'package:flutter_app/scoped_model/auth.dart';
import 'package:flutter_app/utils/dio_http.dart';
import 'package:flutter_app/utils/scoped_model_helper.dart';
import 'package:flutter_app/widgets/common_swiper.dart';
import 'package:flutter_app/widgets/common_title.dart';
import 'package:flutter_app/widgets/tags.dart';
import 'package:flutter_app/widgets/toast_common.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:share/share.dart';

class HouseDetailPage extends StatefulWidget {
  const HouseDetailPage({Key? key, required this.roomId}) : super(key: key);
  final String roomId;
  @override
  _HouseDetailPageState createState() => _HouseDetailPageState();
}

List _list = [
  {
    "imgSrc": 'images/banner.png',
    "title": "111111111111111111111",
    "from": '网易新闻',
    "time": '2021',
    "pushUrl": '/login'
  },
  {
    "imgSrc": 'images/banner.png',
    "title": "2222",
    "from": '网易新闻',
    "time": '2022',
    "pushUrl": '/login'
  },
  {
    "imgSrc": 'images/banner.png',
    "title": "2222",
    "from": '网易新闻',
    "time": '2022',
    "pushUrl": '/login'
  },
  {
    "imgSrc": 'images/banner.png',
    "title": "2222",
    "from": '网易新闻',
    "time": '2022',
    "pushUrl": '/login'
  },
  {
    "imgSrc": 'images/banner.png',
    "title":
        "This site hosts Flutter's API documentation. Other documentation can be found at the following locations:",
    "from": '网易新闻',
    "time": '2022',
    "pushUrl": '/login'
  },
];

class _HouseDetailPageState extends State<HouseDetailPage> {
  late RoomDetailData data;
// 收藏状态
  late bool isCollected = false;
  // 文字展开状态
  late bool showAllText = false;
  String token = '';
  late bool isLogin;

  _getData() async {
    var res = await DioHttp.of(context).get('/houses/${widget.roomId}');
    var resMap = json.decode(res.toString());
    var detailData = resMap["body"];
    var roomDetailData = RoomDetailData.fromJson(detailData);
    setState(() {
      data = roomDetailData;
    });
  }

  // 判断是否收藏
  _isCollect() async {
    var auth = ScopedHelperModel.getModel<AuthModel>(context);
    var _token = auth.token;
    var res = await DioHttp.of(context)
        .get('/user/favorites/${widget.roomId}', null, _token);
    var resMap = json.decode(res.toString());
    String desc = resMap["description"] ?? "内部错误";
    var status = resMap['status'];
    if (status.toString().startsWith('2')) {
      setState(() {
        isCollected = true;
      });
    } else {
      setState(() {
        isCollected = false;
      });
    }
  }

  @override
  void didChangeDependencies() {
    _isCollect();
    _getData();

    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    var auth = ScopedHelperModel.getModel<AuthModel>(context);
    setState(() {
      token = auth.token;
      isLogin = auth.isLogin;
    });
    bool _showTextTool = data.subTitle!.length > 100;
    var mainColor = Theme.of(context).primaryColor;
    var shapeBorder =
        RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.0));
// 添加收藏
    _collect() async {
      if (!isLogin) Navigator.pushNamed(context, '/login');

      if (isLogin) {
        if (!isCollected) {
          var res = await DioHttp.of(context)
              .post('/user/favorites/${widget.roomId}', null, token);
          var resMap = json.decode(res.toString());
          String desc = resMap["description"] ?? "内部错误";
          var status = resMap['status'];
          if (status.toString().startsWith('2')) {
            setState(() {
              isCollected = !isCollected;
            });
            ToastCommon.showToast(desc);
          } else {
            EasyLoading.showError(desc);
          }
        } else {
          // 删除收藏
          var res = await DioHttp.of(context)
              .delete('/user/favorites/${widget.roomId}', null, token);
          var resMap = json.decode(res.toString());
          String desc = resMap["description"] ?? "内部错误";
          var status = resMap['status'];
          if (status.toString().startsWith('2')) {
            setState(() {
              isCollected = !isCollected;
            });
            ToastCommon.showToast(desc);
          } else {
            EasyLoading.showError(desc);
          }
        }
      }
    }

    return Scaffold(
      // bottomSheet: Text('1111'),
      appBar: AppBar(
        title: Text(data.title!),
        actions: [
          IconButton(
              // 分享
              onPressed: () {
                Share.share('check out my website https://example.com',
                    subject: 'Look what I made!');
              },
              icon: const Icon(Icons.share))
        ],
      ),
      body: Stack(
        children: [
          ListView(
            children: [
              SwiperCom(
                images: data.houseImgs ?? [],
              ),
              CommonTitle(title: data.title ?? ''),
              Container(
                padding: const EdgeInsets.only(left: 10.0),
                child: Row(
                  children: [
                    Text(
                      data.price.toString(),
                    ),
                    const Text('元/月（押一付三）')
                  ],
                ),
              ),
              Container(
                padding:
                    const EdgeInsets.only(left: 10.0, top: 8.0, bottom: 10.0),
                child: Wrap(
                  children: data.tags!.map((e) => TagsWidget(e)).toList(),
                ),
              ),
              const Divider(
                indent: 10.0,
                endIndent: 10.0,
                color: Colors.grey,
              ),
              Container(
                padding:
                    const EdgeInsets.only(left: 10.0, top: 8.0, bottom: 10.0),
                child: Wrap(
                  children: [
                    BaseInfoItem(
                      content: '面积:${data.size}平方米',
                    ),
                    BaseInfoItem(
                      content: '楼层:${data.floor}',
                    ),
                    BaseInfoItem(
                      content: '房型:${data.roomType}',
                    ),
                    BaseInfoItem(
                      content: '装修:${data.decorationType ?? '普通'}',
                    ),
                    BaseInfoItem(
                      content: '小区:${data.community ?? '无'}',
                    ),
                  ],
                ),
              ),
              const CommonTitle(title: '房屋配置'),
              // RoomConfiguration(),
              HouseConfigurationList(
                list: data.applicances,
              ),
              const CommonTitle(title: '房屋概况'),
              Container(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      data.subTitle ?? '暂无房屋概况',
                      maxLines: showAllText ? null : 5,
                      overflow: showAllText
                          ? TextOverflow.fade
                          : TextOverflow.ellipsis,
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        _showTextTool
                            ? GestureDetector(
                                onTap: () {
                                  setState(() {
                                    showAllText = !showAllText;
                                  });
                                },
                                child: Row(
                                  children: [
                                    Text(showAllText ? '收起' : '展开'),
                                    Icon(showAllText
                                        ? Icons.keyboard_arrow_up
                                        : Icons.keyboard_arrow_down)
                                  ],
                                ),
                              )
                            : const Text(''),
                        Padding(
                          padding: const EdgeInsets.only(right: 10.0),
                          child: TextButton(
                              onPressed: () {
                                showDialog(
                                    context: context,
                                    builder: (context) {
                                      return const AlertDialog(
                                          title: Text('举报......!'));
                                    });
                              },
                              child: const Text('举报')),
                        ),
                      ],
                    )
                  ],
                ),
                padding: const EdgeInsets.only(left: 10.0),
              ),
              const CommonTitle(title: '猜你喜欢'),
              Column(
                children: _list.map((e) {
                  return InfoItem(data: e);
                }).toList(),
              ),
              Container(
                margin: const EdgeInsets.only(bottom: 120.0),
              ),
            ],
          ),
          /************ 底部栏 ****************/
          Positioned(
              bottom: 0,
              width: MediaQuery.of(context).size.width,
              height: 100,
              child: Container(
                padding: const EdgeInsetsDirectional.fromSTEB(20, 0, 20, 0),
                color: Colors.grey[200],
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    GestureDetector(
                      onTap: () {
                        _collect();
                        // setState(() {
                        //   isCollected = !isCollected;
                        // });
                      },
                      child: Container(
                        height: 50,
                        width: 50,
                        margin: const EdgeInsets.only(right: 10.0),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Icon(
                              isCollected ? Icons.star : Icons.star_border,
                              color: mainColor,
                            ),
                            isCollected ? const Text('已收藏') : const Text('收藏')
                          ],
                        ),
                      ),
                    ),
                    Expanded(
                      child: Container(
                        margin: const EdgeInsets.only(right: 10.0),
                        height: 50,
                        child: ElevatedButton(
                            onPressed: () {},
                            style: ElevatedButton.styleFrom(
                                primary: Colors.blueAccent, shape: shapeBorder),
                            child: const Text(
                              '联系房东',
                              style: TextStyle(
                                  color: Colors.white, fontSize: 16.0),
                            )),
                      ),
                    ),
                    Expanded(
                      child: SizedBox(
                        height: 50,
                        child: ElevatedButton(
                            style: ElevatedButton.styleFrom(shape: shapeBorder),
                            onPressed: () {},
                            child: const Text(
                              '预约看房',
                              style: TextStyle(
                                  color: Colors.white, fontSize: 16.0),
                            )),
                      ),
                    )
                  ],
                ),
              ))
        ],
      ),
    );
  }
}

class BaseInfoItem extends StatelessWidget {
  const BaseInfoItem({
    Key? key,
    required this.content,
  }) : super(key: key);

  final String content;

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.only(bottom: 10.0),
      child: Text(content),
      width: (MediaQuery.of(context).size.width - 3 * 10.0) / 2,
    );
  }
}
